package com.huhu.objects;

import org.andengine.engine.camera.Camera;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.huhu.interfaces.IPlayer;
import com.huhu.manager.ResourcesManager;

public abstract class AirCraft extends Sprite implements IPlayer{
	private Body body;
	private boolean canRun = false;
	private boolean direction = true;
	private boolean die = false;
	private int footContact = 0;

	public AirCraft(float pX, float pY, VertexBufferObjectManager vbom,
			Camera camera, PhysicsWorld physicsWorld) {
		super(pX, pY, ResourcesManager.getInstance().aircraft_region, vbom);

		createPhysics(camera, physicsWorld);
		camera.setChaseEntity(this);
	}

	public abstract void onDie();
	public void jump(){
		
	}

	private void createPhysics(final Camera camera, PhysicsWorld physicsWorld) {
		final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0, 0);
		body = PhysicsFactory.createBoxBody(physicsWorld, this,
				BodyType.DynamicBody, FIXTURE_DEF);
		body.setUserData("player");
		body.setFixedRotation(true);

		physicsWorld.registerPhysicsConnector(new PhysicsConnector(this, body,
				true, false) {
			@Override
			public void onUpdate(float pSecondsElapsed) {
				// TODO Auto-generated method stub
				super.onUpdate(pSecondsElapsed);
				camera.onUpdate(0.1f);
				if (!die) {
					if (canRun) {
						if (direction) {
							body.setLinearVelocity(new Vector2(7, body
									.getLinearVelocity().y));
						} else {
							body.setLinearVelocity(new Vector2(-7, body
									.getLinearVelocity().y));
						}
					} else {
						body.setLinearVelocity(new Vector2(0, body
								.getLinearVelocity().y));
					}
				}
				if (die) {
					body.setLinearVelocity(new Vector2(0, body
							.getLinearVelocity().y));
					ResourcesManager.getInstance().replaceAircraftDead();
					onDie();
				}
			}
		});
	}

	public void setRunning() {
		canRun = true;
	}

	public void setStopping() {
		canRun = false;
	}

	public void setDirection(boolean direction) {
		this.direction = direction;
	}

	public float getCenterX() {
		return (this.getX() + this.getWidth() / 2);
	}
	
	public void setDie(boolean die){
		this.die = die;
	}
	public boolean isDie(){
		return this.die;
	}
	
	public void increaseFootContacts() {
		footContact++;
	}

	public void decreaseFootContacts() {
		footContact--;
	}
}
